package es.uji.viselab.image.process;

import static com.googlecode.javacv.cpp.opencv_calib3d.CV_CALIB_CB_ADAPTIVE_THRESH;
import static com.googlecode.javacv.cpp.opencv_calib3d.CV_CALIB_CB_FILTER_QUADS;
import static com.googlecode.javacv.cpp.opencv_calib3d.cvFindChessboardCorners;
import static com.googlecode.javacv.cpp.opencv_core.CV_TERMCRIT_EPS;
import static com.googlecode.javacv.cpp.opencv_core.CV_TERMCRIT_ITER;
import static com.googlecode.javacv.cpp.opencv_core.cvSize;
import static com.googlecode.javacv.cpp.opencv_core.cvTermCriteria;
import static com.googlecode.javacv.cpp.opencv_imgproc.CV_RGB2GRAY;
import static com.googlecode.javacv.cpp.opencv_imgproc.cvCvtColor;
import static com.googlecode.javacv.cpp.opencv_imgproc.cvFindCornerSubPix;

import java.awt.image.BufferedImage;

import com.googlecode.javacv.cpp.opencv_core;
import com.googlecode.javacv.cpp.opencv_core.CvPoint2D32f;
import com.googlecode.javacv.cpp.opencv_core.CvSize;
import com.googlecode.javacv.cpp.opencv_core.IplImage;

import es.uji.viselab.math.Vector2;

public class ProcessChessBoard  extends ImageProcessing{

	@Override
	public Vector2[] process(BufferedImage bImage) {
		
		
		// http://pastebin.com/hg5FKTiL
		// http://dsynflo.blogspot.com.es/2010/06/simplar-augmented-reality-for-opencv.html
		//
		
		Vector2[] featurePoints = null;
		
		if (bImage != null) {

			int bWidth = 4;
			int bHeight = 4;
			int bSquares = bWidth * bHeight;
			CvSize bSize = cvSize(bWidth, bHeight);

			CvPoint2D32f corners = new CvPoint2D32f(20);
			opencv_core.IplImage image = IplImage.createFrom(bImage);
			int corner_count[] = new int[20];
			int found = cvFindChessboardCorners(image, bSize, corners, corner_count,
					CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS);
			IplImage imageGrey = IplImage.create(image.width(), image.height(), 8, 1);

			cvCvtColor(image, imageGrey, CV_RGB2GRAY);
			int count2 = 0;
			cvFindCornerSubPix(imageGrey, corners, count2, cvSize(11, 11), cvSize(-1, -1),
					cvTermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 30, 0.1));
			count2 = 20;
			if (corner_count[0] == bSquares) {
				featurePoints = new Vector2[4];
				featurePoints[0] = new Vector2();
				featurePoints[1] = new Vector2();
				featurePoints[2] = new Vector2();
				featurePoints[3] = new Vector2();
				featurePoints[0].x = corners.position(0).x();
				featurePoints[0].y = corners.position(0).y();
				featurePoints[1].x = corners.position(bWidth-1).x();
				featurePoints[1].y = corners.position(bWidth-1).y();
				featurePoints[2].x = corners.position(bSquares-1).x();
				featurePoints[2].y = corners.position(bSquares-1).y();
				featurePoints[3].x = corners.position(bSquares-bWidth).x();
				featurePoints[3].y = corners.position(bSquares-bWidth).y();
			}
		}
		return featurePoints;
	}
}
